/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverse(ListNode *head, int k){
        ListNode *newhead = head;
        ListNode *step = head->next;
        ListNode *curnode = NULL;
        while(--k){
            curnode = step;
            step = step->next;
            curnode->next = newhead;
            newhead = curnode;
        }
        head->next = step;
        return newhead;
    }

    ListNode* reverseKGroup(ListNode *head, int k) {
     	if( !head || k < 0)
            return NULL;
        if( k == 1)
            return head;
        
        ListNode *lasttail = head;
        ListNode *newhead = head;
		int len = 0;
        
        while( lasttail ){
            lasttail = lasttail->next;
            len++;
        }

        if( len < k )
            return head;

        newhead = reverse(head, k);
        lasttail = head;
        head = head->next;
        int m = len/k;
        int i= 1;
        for(i; i < m; i++){
            lasttail->next = reverse(head, k);
            lasttail = head;
            head = head->next;
        }

		return newhead;   
    }
};
